package com.soup.lab.basic.initialization;

import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * Java类初始化顺序测试
 */
public class InitializationOrderTestCase {

    @Test
    public void testInitializationTrace() {
        new Child();
    }

    @Test
    public void testError() {
        System.out.println(new C().get("a"));
    }

    private static class A {
        Map<String, Object> cacheA = new HashMap<>();

        A() {
            init();
        }

        protected void init() {}

        public Object get(String key) {
            return cacheA.getOrDefault(key, getDefault(key));
        }
        protected Object getDefault(String key) {
            return null;
        }
        public void registerA(String key, Object val) {
            cacheA.put(key, val);
        }
    }

    private static class B extends A {
        Map<String, Object> cacheB = new HashMap<>();
        public Object getDefault(String key) {
            return cacheB.get(key);
        }
        public void registerB(String key, Object val) {
            cacheB.put(key, val);
        }
    }

    private static class C extends B {
        @Override
        protected void init() {
            registerB("a", 123);
        }
    }

}
